package com.solarStruggle.graphics

import java.awt.Image
import javax.swing.ImageIcon
import java.io.{BufferedReader, ByteArrayInputStream, ByteArrayOutputStream, InputStream, InputStreamReader}
import org.apache.batik.transcoder.image.PNGTranscoder
import org.apache.batik.transcoder.{TranscodingHints, TranscoderInput, TranscoderOutput, SVGAbstractTranscoder}

class Svg(width: Int, height: Int, input: InputStream, teamColor: String)
extends ImageGenerator(width, height) {
  
  /**
   * Helper method to convert a .svg input into an AWT image so it can be displayed
   */
  override def createImage(): BufferedImage = {
    
    val reader = new BufferedReader(new InputStreamReader(input))
    val sb = new StringBuilder()
    
    var line = reader.readLine()
    while(line != null) {
      sb.append(line.replaceAll("#ff00ff", teamColor))
      line = reader.readLine
    }
    
    /**
     * Stupid work-around... Scala can't access the static fields for the hint keys for some reason,
     * so use reflection instead
     */
    def getHintKey(name: String) = 
    	Thread.currentThread.getContextClassLoader.
    		loadClass("org.apache.batik.transcoder.SVGAbstractTranscoder").
    		getDeclaredField(name).
    		get(null).asInstanceOf[TranscodingHints.Key]
    
    val transcoder = new PNGTranscoder
    transcoder.addTranscodingHint(getHintKey("KEY_WIDTH"), width)
    transcoder.addTranscodingHint(getHintKey("KEY_HEIGHT"), height)
    
    val outputStream = new ByteArrayOutputStream
    
    transcoder.transcode(new TranscoderInput(new ByteArrayInputStream(sb.toString.getBytes("UTF-8"))), new TranscoderOutput(outputStream))
    
    return new ImageIcon(outputStream.toByteArray).getImage.asInstanceOf[BufferedImage]
  }
  
}